﻿<%@ WebHandler Language="C#" Class="MakeCalendarHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

//Description:日历维护处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:longb
//create Date:2022-04-25
public class MakeCalendarHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    MakeCalendarBusiness makecalendar = new MakeCalendarBusiness();
    #region 页面初始化
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "SaveOrUpdateMainCaData": //保存日历主表信息
                    SaveOrUpdateMainCaData(context);
                    break;
                case "DaleteMainCaData": //删除日历主表信息
                    DaleteMainCaData(context);
                    break;
                case "SaveOrUpdateDetaileCaData": //保存日历天安排信息
                    SaveOrUpdateDetaileCaData(context);
                    break;
                case "GetMainCaData": //获取所有日历主表信息
                    GetMainCaData(context);
                    break;
                case "GetDetailCaData": //获取对应日历明细信息
                    GetDetailCaData(context);
                    break;
                case "DeleteDetailCaData": //删除对应日历明细信息
                    DeleteDetailCaData(context);
                    break;
                case "BatchHolidaySet": //周六，周日批量设定
                    BatchHolidaySet(context);
                    break;
                case "SaveRelationFactoryData"://日历-工厂关系设置
                    SaveRelationFactoryData(context);
                    break;
                case "GetRelationFactoryData"://查询日历-工厂关系数据
                    GetRelationFactoryData(context);
                    break;
                case "getResource"://查询设备信息
                    getResource(context);
                    break;    
                case "SaveRelationResourceData"://日历-设备关系设置
                    SaveRelationResourceData(context);
                    break;
                case "GetRelationResourceData"://查询日历-设备关系数据
                    GetRelationResourceData(context);
                    break;
                case"getWorkCenter":
                    getWorkCenter(context);
                    break;   
                case "SaveRelationWorkcenterData"://日历-工区关系设置
                    SaveRelationWorkcenterData(context);
                    break;
                case "GetRelationWorkcenterData"://查询日历-工区关系数据
                    GetRelationWorkcenterData(context);
                    break;
                case "getTeam":
                    getTeam(context);
                    break;    
                case "SaveRelationTeamData"://日历-班组关系设置
                    SaveRelationTeamData(context);
                    break;
                case "GetRelationTeamData"://查询日历-班组关系数据
                    GetRelationTeamData(context);
                    break;
                case "GetEmployees":
                    GetEmployees(context);
                    break;   
                case "SaveRelationEmployeeData"://日历-人员关系设置
                    SaveRelationEmployeeData(context);
                    break;
                case "GetRelationEmployeeData"://查询日历-人员关系数据
                    GetRelationEmployeeData(context);
                    break;    
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    #endregion

    #region 方法
    /// <summary>
    /// //保存日历主表信息
    /// </summary>
    /// <param name="context"></param>
    public void SaveOrUpdateMainCaData(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["CaData"].ToString());
        dt.Columns.Add("CREATEEMPLOYEEID");
        dt.Rows[0]["CREATEEMPLOYEEID"] = m_UserInfo.EmployeeID;
        uMESProcessResult result = new uMESProcessResult();
        //ID存在，更新，否则新增
        if (dt.Rows.Count > 0 && !string.IsNullOrWhiteSpace(dt.Rows[0]["MAKECALENDARID"].ToString()))
        {
            //更新
            List<ExcuteEntity> List = new List<ExcuteEntity>();
            var InsertEntity = new ExcuteEntity("MAKECALENDAR", ExcuteEntity.ExcuteTypeEnum.update);
            List<FieldEntity> updateList = new List<FieldEntity>();
            List<FieldEntity> whereList = new List<FieldEntity>();
            whereList.Add(new FieldEntity("MAKECALENDARID", dt.Rows[0]["MAKECALENDARID"].ToString(), FieldEntity.FieldTypeEnum.Str));
            updateList.Add(new FieldEntity("MAKECALENDARNAME", dt.Rows[0]["MAKECALENDARNAME"].ToString(), FieldEntity.FieldTypeEnum.Str));
            updateList.Add(new FieldEntity("ISUSE", dt.Rows[0]["ISUSE"].ToString(), FieldEntity.FieldTypeEnum.Str));
            updateList.Add(new FieldEntity("DESCRIPTION", dt.Rows[0]["DESCRIPTION"].ToString(), FieldEntity.FieldTypeEnum.Str));
            InsertEntity.ExcuteFileds = updateList;
            InsertEntity.WhereFileds = whereList;
            List.Add(InsertEntity);
            result.Result = DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(List);
            result.ReturnData = dt.Rows[0]["MAKECALENDARID"].ToString();
        }
        else
        {
            DataTable dtt = DatabaseHelper.Query_ReturnDatTable(string.Format("select * from MAKECALENDAR where MAKEYEAR='{0}' and MAKECALENDARNAME='{1}'", dt.Rows[0]["MAKEYEAR"].ToString(),dt.Rows[0]["MAKECALENDARNAME"].ToString()));
            if (dtt.Rows.Count>0) {
                result.Message = "保存失败，同一年份已维护该日历模板";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            List<ExcuteEntity> List = new List<ExcuteEntity>();
            string MainID=Guid.NewGuid().ToString();
            var InsertEntity = new ExcuteEntity("MAKECALENDAR", ExcuteEntity.ExcuteTypeEnum.insert);
            List<FieldEntity> InsertList = new List<FieldEntity>();
            InsertList.Add(new FieldEntity("MAKECALENDARID", MainID, FieldEntity.FieldTypeEnum.Str));
            InsertList.Add(new FieldEntity("MAKECALENDARNAME", dt.Rows[0]["MAKECALENDARNAME"].ToString(), FieldEntity.FieldTypeEnum.Str));
            InsertList.Add(new FieldEntity("ISUSE", dt.Rows[0]["ISUSE"].ToString(), FieldEntity.FieldTypeEnum.Str));
            InsertList.Add(new FieldEntity("DESCRIPTION", dt.Rows[0]["DESCRIPTION"].ToString(), FieldEntity.FieldTypeEnum.Str));
            InsertList.Add(new FieldEntity("CREATEDATE", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
            InsertList.Add(new FieldEntity("CREATEEMPLOYEEID", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
            InsertList.Add(new FieldEntity("MAKEYEAR", dt.Rows[0]["MAKEYEAR"].ToString(), FieldEntity.FieldTypeEnum.Str));
            InsertEntity.ExcuteFileds = InsertList;
            List.Add(InsertEntity);
            result.Result = DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(List);
            result.ReturnData = MainID;
        }
        if (result.Result) result.Message = "保存成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 删除日历主表信息
    /// </summary>
    /// <param name="context"></param>
    public void DaleteMainCaData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        DataTable dt = commonBusiness.GetTableInfo("RESOURCEDEF", "MAKECALENDARID", MID);
        uMESProcessResult result = new uMESProcessResult();
        List<ExcuteEntity> List = new List<ExcuteEntity>();
        if (dt.Rows.Count==0)
        {
            if (!string.IsNullOrWhiteSpace(MID))
            {
                List<FieldEntity> delFE = new List<FieldEntity>();
                delFE.Add(new FieldEntity("MAKECALENDARID", MID, FieldEntity.FieldTypeEnum.Str));
                var mainEntity = new ExcuteEntity("MAKECALENDAR", ExcuteEntity.ExcuteTypeEnum.del);
                mainEntity.WhereFileds = delFE;
                List.Add(mainEntity);
                var detailEntity = new ExcuteEntity("makecalendardetail", ExcuteEntity.ExcuteTypeEnum.del);
                detailEntity.WhereFileds = delFE;
                List.Add(detailEntity);
                result.Result = DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(List);
                if (result.Result) result.Message = "删除成功";
            }
            else { result.Message = "请选择要删除的记录"; }
       }else{result.Message = "日历已关联使用，删除失败";}
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取所有日历主表信息
    /// </summary>
    /// <param name="context"></param>
    public void GetMainCaData(HttpContext context)
    {
        //DataTable dt = commonBusiness.GetTableInfo("MAKECALENDAR", "1", "1");
        //dt.DefaultView.Sort = "MAKEYEAR ASC";
        //dt = dt.DefaultView.ToTable();
        var MAKEYEAR=context.Request["MAKEYEAR"].ToString();
        var MAKECALENDARNAME = context.Request["MAKECALENDARNAME"].ToString();
        var sql = @"SELECT m.MAKECALENDARID,m.MAKECALENDARNAME,m.MAKEYEAR,m.DESCRIPTION,m.ISUSE,e.fullname,to_char(m.CREATEDATE,'yyyy-MM-dd hh24:mi:ss') CREATEDATE
                    FROM MAKECALENDAR m 
                    LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =m.CREATEEMPLOYEEID 
                    WHERE 1=1 ";
        if (!string.IsNullOrWhiteSpace(MAKEYEAR)) { sql += " AND m.MAKEYEAR='" + MAKEYEAR + "'"; }
        if (!string.IsNullOrWhiteSpace(MAKECALENDARNAME)) { sql += " AND m.MAKECALENDARNAME like '%" + MAKECALENDARNAME + "%'"; }
        sql += " ORDER BY m.MAKEYEAR DESC";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        uMESProcessResult result = new uMESProcessResult();
        if (dt.Rows.Count > 0) { result.DBTable = dt; result.Result = true; }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 保存日历天安排信息
    /// </summary>
    /// <param name="context"></param>
    public void SaveOrUpdateDetaileCaData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["DetaileCaData"].ToString());
        dt.Columns.Add("CREATEEMPLOYEEID");
        dt.Rows[0]["CREATEEMPLOYEEID"] = m_UserInfo.EmployeeID;
        string continueDay = dt.Rows[0]["continueDay"].ToString();
        List<ExcuteEntity> List = new List<ExcuteEntity>();
        //先删除
        var HOLIDAYDATE = DateTime.Parse(dt.Rows[0]["startDate"].ToString()).Date;
        string strWhere = "  and MAKECALENDARID='" + dt.Rows[0]["MakeCalendarID"].ToString() + "' and HOLIDAYDATE>= " + string.Format("to_date('{0}','yyyy-mm-dd')", HOLIDAYDATE.ToString("yyyy-MM-dd")) + " AND HOLIDAYDATE<=" + string.Format("to_date('{0}','yyyy-mm-dd')", HOLIDAYDATE.AddDays(Convert.ToInt32(continueDay) - 1).ToString("yyyy-MM-dd"));
        var exuteEntity = new ExcuteEntity("makecalendardetail", ExcuteEntity.ExcuteTypeEnum.del);
        exuteEntity.strWhere = strWhere;
        exuteEntity.WhereFileds = new List<FieldEntity>();
        List.Add(exuteEntity);
        //后新增
        if (!string.IsNullOrWhiteSpace(continueDay))
        {
            for (var i = 0; i < Convert.ToInt32(continueDay); i++)
            {
                var InsertEntity = new ExcuteEntity("makecalendardetail", ExcuteEntity.ExcuteTypeEnum.insert);
                List<FieldEntity> InsertList = new List<FieldEntity>();
                InsertList.Add(new FieldEntity("MAKECALENDARDETAILID", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("MAKECALENDARID", dt.Rows[0]["MakeCalendarID"].ToString(), FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("HOLIDAYDATE", HOLIDAYDATE.Date.AddDays(i).ToString("yyyy-MM-dd"), FieldEntity.FieldTypeEnum.DateTime));
                InsertList.Add(new FieldEntity("HOLIDAYNAME", dt.Rows[0]["holidayName"].ToString(), FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("CREATEEMPLOYEEID", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("ISUSE","0", FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("CREATEDATE", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
                InsertEntity.ExcuteFileds = InsertList;
                List.Add(InsertEntity);
            }
        }
        result.Result = DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(List);
        if (result.Result) result.Message = "保存成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取对应日历明细信息
    /// </summary>
    /// <param name="context"></param>
    public void GetDetailCaData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        string date = context.Request["Date"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        List<FieldEntity> conditionList = new List<FieldEntity>();
        conditionList.Add(new FieldEntity("MAKECALENDARID", MID, FieldEntity.FieldTypeEnum.Str));
        if (!string.IsNullOrWhiteSpace(date))
        {
            conditionList.Add(new FieldEntity("HOLIDAYDATE", DateTime.Parse(date).ToString("yyyy-MM-dd"), FieldEntity.FieldTypeEnum.DateTime));
        }
        var exuteEntity = new ExcuteEntity("makecalendardetail", ExcuteEntity.ExcuteTypeEnum.selectAll);
        exuteEntity.WhereFileds = conditionList;
        DataTable dt = DatabaseAccess.DBUtility.DatabaseHelper.QueryDataByEntity(exuteEntity);
        if (dt.Rows.Count > 0) { result.DBTable = dt; result.Result = true; result.Message = "查询成功"; }
        else if (!string.IsNullOrWhiteSpace(date)) { result.Result = true; }
        else { result.Message = "查询不到假期日历信息，请先维护"; }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 删除对应日历【天】明细信息
    /// </summary>
    /// <param name="context"></param>
    public void DeleteDetailCaData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["DetaileCaData"].ToString());
        string continueDay = dt.Rows[0]["continueDay"].ToString();//持续天数
        if (dt.Rows.Count > 0)
        {
            List<ExcuteEntity> List = new List<ExcuteEntity>();
            var HOLIDAYDATE = DateTime.Parse(dt.Rows[0]["startDate"].ToString()).Date;
            string strWhere = " and MAKECALENDARID='" + dt.Rows[0]["MakeCalendarID"].ToString() + "' and HOLIDAYDATE>= " + string.Format("to_date('{0}','yyyy-mm-dd')", HOLIDAYDATE.ToString("yyyy-MM-dd")) + " AND HOLIDAYDATE<=" + string.Format("to_date('{0}','yyyy-mm-dd')", HOLIDAYDATE.AddDays(Convert.ToInt32(continueDay) - 1).ToString("yyyy-MM-dd"));
            var exuteEntity = new ExcuteEntity("makecalendardetail", ExcuteEntity.ExcuteTypeEnum.del);
            exuteEntity.strWhere = strWhere;
            exuteEntity.WhereFileds = new List<FieldEntity>();
            List.Add(exuteEntity);
            result.Result = DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(List);
            if (result.Result) result.Message = "删除成功";
        }
        else { result.Message = "请选择要删除的记录"; }
        context.Response.Write(JsonConvert.SerializeObject(result));

    }
    /// <summary>
    /// 周六，周日批量设定
    /// </summary>
    /// <param name="context"></param>
    public void BatchHolidaySet(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        string Year = context.Request["Year"].ToString();
        string Type = context.Request["Type"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        List<ExcuteEntity> List = new List<ExcuteEntity>();
        var YearStarte = Convert.ToDateTime(Year + "-01-01");
        //先查询判断是否存在维护
        List<FieldEntity> conditionList = new List<FieldEntity>();
        conditionList.Add(new FieldEntity("MAKECALENDARID", MID, FieldEntity.FieldTypeEnum.Str));
        var exuteEntity = new ExcuteEntity("makecalendardetail", ExcuteEntity.ExcuteTypeEnum.selectAll);
        var strWhere = " and to_char(HOLIDAYDATE,'yyyy')= '" + Year + "' AND TO_CHAR(TO_DATE(to_CHAR(HOLIDAYDATE,'yyyy/mm/dd'),'YYYY-MM-DD'),'d')='" + (Type == "0" ? "7" : "1") + "'";
        exuteEntity.WhereFileds = conditionList;
        exuteEntity.strWhere = strWhere;
        DataTable dt = DatabaseAccess.DBUtility.DatabaseHelper.QueryDataByEntity(exuteEntity);
        if (dt.Rows.Count > 0) {
            List = getDetailDeleteEntity(MID, Year, Type, List);
        } else {
            List = GetMakeCalendarDetailEntity(MID, YearStarte, Type, List);
        }
        result.Result = DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(List);
        if (result.Result) result.Message = "设置成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    public List<ExcuteEntity> GetMakeCalendarDetailEntity(string MID, DateTime YearMonth, string type, List<ExcuteEntity> List)
    {
        var yearDays = DateTime.IsLeapYear(YearMonth.Year) ? 366 : 365;
        for (var i = 0; i < yearDays; i++)
        {
            var date = YearMonth.AddDays(i);
            if (("1".Equals(type) && date.DayOfWeek == DayOfWeek.Sunday) || ("0".Equals(type) && date.DayOfWeek == DayOfWeek.Saturday))
            {
                var InsertEntity = new ExcuteEntity("makecalendardetail", ExcuteEntity.ExcuteTypeEnum.insert);
                List<FieldEntity> InsertList = new List<FieldEntity>();
                InsertList.Add(new FieldEntity("MAKECALENDARDETAILID", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("MAKECALENDARID", MID, FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("HOLIDAYDATE", date, FieldEntity.FieldTypeEnum.DateTime));
                InsertList.Add(new FieldEntity("HOLIDAYNAME", (type=="1"?"周日休息":"周六休息"), FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("CREATEEMPLOYEEID", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("ISUSE", "0", FieldEntity.FieldTypeEnum.Str));
                InsertList.Add(new FieldEntity("CREATEDATE", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
                InsertEntity.ExcuteFileds = InsertList;
                List.Add(InsertEntity);
            }
        }
        return List;
    }
    public List<ExcuteEntity> getDetailDeleteEntity(string MAKECALENDARID, string Year, string type, List<ExcuteEntity> List)
    {
        List<FieldEntity> deleteList = new List<FieldEntity>();
        deleteList.Add(new FieldEntity("MAKECALENDARID", MAKECALENDARID, FieldEntity.FieldTypeEnum.Str));
        var exuteEntity = new ExcuteEntity("makecalendardetail", ExcuteEntity.ExcuteTypeEnum.del);
        exuteEntity.WhereFileds = deleteList;
        exuteEntity.strWhere = "  and to_char(HOLIDAYDATE,'yyyy')= '" + Year+"' AND TO_CHAR(TO_DATE(to_CHAR(HOLIDAYDATE,'yyyy/mm/dd'),'YYYY-MM-DD'),'d')='" + (type=="0"?"7":"1") + "'";
        List.Add(exuteEntity);
        return List;
    }
    /// <summary>
    /// 日历-工厂关系设置
    /// </summary>
    /// <param name="context"></param>
    public void SaveRelationFactoryData(HttpContext context) 
    {
        string MID = context.Request["MID"].ToString();
        string FACTORYID = context.Request["FACTORYID"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var arrList = new ArrayList();
        foreach (var FID in FACTORYID.Split(',')) {
            arrList.Add(string.Format("UPDATE FACTORY SET MAKECALENDARID='{0}' where FACTORYID='{1}'", MID,FID));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(arrList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询日历-工厂关系数据
    /// </summary>
    /// <param name="context"></param>
    public void GetRelationFactoryData(HttpContext context) 
    {
        string MID = context.Request["MID"].ToString();
        var selSQL = @"SELECT * FROM FACTORY f WHERE f.MAKECALENDARID='"+MID+"' ";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(selSQL);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }

    public void getResource(HttpContext context) 
    {
        string Name = context.Request["Name"].ToString();
        var selSQL = @"SELECT r.RESOURCEID ID,r.DESCRIPTION||'('||r.RESOURCENAME ||')'NAME FROM RESOURCEDEF r
                    WHERE r.FACTORYID ='"+m_UserInfo.FactoryID+"' AND ( r.RESOURCEENAME LIKE '%" + Name + "%' OR r.DESCRIPTION LIKE '%" + Name + "%') ";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(selSQL);
        uMESProcessResult result = new uMESProcessResult();
        result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 日历-设备关系设置
    /// </summary>
    /// <param name="context"></param>
    public void SaveRelationResourceData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        string RESOURCEID = context.Request["RESOURCEID"].ToString();
        string type = context.Request["type"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var arrList = new ArrayList();
        foreach (var RID in RESOURCEID.Split(','))
        {
            if (type=="1")
            {
                arrList.Add(string.Format("UPDATE RESOURCEDEF SET NextMakeCalendarID='' where RESOURCEID='{0}'", RID));
            }
            else if (type == "0")
            {
                arrList.Add(string.Format("UPDATE RESOURCEDEF SET MAKECALENDARID='' where RESOURCEID='{0}'",RID));
            }
            else {
                arrList.Add(string.Format("UPDATE RESOURCEDEF SET MAKECALENDARID='{0}',NextMakeCalendarID='{1}' where RESOURCEID='{2}'", MID, context.Request["NEXTMID"].ToString(), RID));
            }
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(arrList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void GetRelationResourceData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var selSQL = @"SELECT f.*,m.MAKECALENDARNAME,m2.MAKECALENDARNAME NEXTMAKECALENDARNAME FROM RESOURCEDEF f 
                        LEFT JOIN MAKECALENDAR m ON m.MAKECALENDARID =f.MAKECALENDARID 
                        LEFT JOIN MAKECALENDAR m2 ON m2.MAKECALENDARID =f.NEXTMAKECALENDARID  
                        WHERE f.MAKECALENDARID='" + MID + "' OR NextMakeCalendarID='" + MID + "'";
        //DataTable dt = DatabaseHelper.Query_ReturnDatTable(selSQL);
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = selSQL;
        result = DatabaseHelper.RunProcedureForPage(paraPage);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public void getWorkCenter(HttpContext context)
    {
        var selSQL = @" SELECT * FROM WORKCENTER w WHERE w.FACTORYID='"+m_UserInfo.FactoryID+"'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(selSQL);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    
    /// <summary>
    /// 
    /// </summary>
    public void SaveRelationWorkcenterData(HttpContext context) 
    {
        string MID = context.Request["MID"].ToString();
        string WORKCENTERID = context.Request["WORKCENTERID"].ToString();
        var WCSQL = @"SELECT DISTINCT wc.WORKCENTERID,wc.WORKCENTERNAME,e.EMPLOYEEID FROM EMPLOYEE e 
                LEFT JOIN sessionvalues sv ON sv.sessionvaluesid = e.sessionvaluesid 
                LEFT JOIN workcenter wc ON wc.workcenterid = sv.workcenterid 
                WHERE wc.WORKCENTERID ='" + WORKCENTERID + "'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(WCSQL);
        uMESProcessResult result = new uMESProcessResult();
        var arrList = new ArrayList();
        foreach (DataRow row in dt.Rows)
        {
            arrList.Add(string.Format("UPDATE EMPLOYEE SET MAKECALENDARID='{0}' where EMPLOYEEID='{1}'", MID, row["EMPLOYEEID"].ToString()));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(arrList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void GetRelationWorkcenterData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        var WCSQL = @"SELECT DISTINCT wc.WORKCENTERID,wc.WORKCENTERNAME FROM EMPLOYEE e 
            LEFT JOIN sessionvalues sv ON sv.sessionvaluesid = e.sessionvaluesid 
            LEFT JOIN workcenter wc ON wc.workcenterid = sv.workcenterid 
            WHERE e.MAKECALENDARID ='" + MID + "'  AND wc.WORKCENTERID IS NOT NULL ";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(WCSQL);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    //-----------------------------------------------------
    public void getTeam(HttpContext context)
    {
        var selSQL = @"  SELECT t.TEAMID,t.TEAMNAME FROM TEAM t WHERE t.FACTORYID='" + m_UserInfo.FactoryID + "'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(selSQL);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    /// <summary>
    /// 
    /// </summary>
    public void SaveRelationTeamData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        string TEAMID = context.Request["TEAMID"].ToString();
        var WCSQL = @"SELECT te.TEAMID ,te.TEAMNAME,e.EMPLOYEEID FROM EMPLOYEE e 
                    LEFT JOIN sessionvalues sv ON sv.sessionvaluesid = e.sessionvaluesid 
                    LEFT JOIN (SELECT  t.teamname,t.teamid,te.employeeid,t.shiftid FROM teamemployee te 
		                       LEFT JOIN team t  ON t.teamid = te.teamid  
	                    ) te  ON te.employeeid = e.employeeid AND ROWNUM = 1 
                     WHERE te.TEAMID='" + TEAMID + "'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(WCSQL);
        uMESProcessResult result = new uMESProcessResult();
        var arrList = new ArrayList();
        foreach (DataRow row in dt.Rows)
        {
            arrList.Add(string.Format("UPDATE EMPLOYEE SET MAKECALENDARID='{0}' where EMPLOYEEID='{1}'", MID, row["EMPLOYEEID"].ToString()));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(arrList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void GetRelationTeamData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        var WCSQL = @"SELECT te.TEAMID ,te.TEAMNAME,e.EMPLOYEEID FROM EMPLOYEE e 
                LEFT JOIN sessionvalues sv ON sv.sessionvaluesid = e.sessionvaluesid 
                LEFT JOIN (SELECT  t.teamname,t.teamid,te.employeeid,t.shiftid FROM teamemployee te 
		                   LEFT JOIN team t  ON t.teamid = te.teamid  
	                ) te  ON te.employeeid = e.employeeid AND ROWNUM = 1 
                 WHERE e.MAKECALENDARID ='"+MID+"' AND te.TEAMID IS NOT NULL";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(WCSQL);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void GetEmployees(HttpContext context) 
    {
        string Name = context.Request["Name"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var EmplSQl = @"SELECT e.EMPLOYEEID ID ,e.FULLNAME||'('||e.EMPLOYEENAME||')' NAME FROM EMPLOYEE e 
            LEFT JOIN sessionvalues sv ON sv.sessionvaluesid = e.sessionvaluesid
            WHERE sv.factoryid ='" + m_UserInfo.FactoryID + "' AND (e.FULLNAME like '%" + Name + "%' OR e.EMPLOYEENAME like '%" + Name + "%')";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(EmplSQl);
        result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    public void SaveRelationEmployeeData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        string EMPLOYEEID = context.Request["EMPLOYEEID"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var arrList = new ArrayList();
        foreach (var EID in EMPLOYEEID.Split(','))
        {
            arrList.Add(string.Format("UPDATE EMPLOYEE SET MAKECALENDARID='{0}' where EMPLOYEEID='{1}'", MID, EID));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(arrList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void GetRelationEmployeeData(HttpContext context)
    {
        string MID = context.Request["MID"].ToString();
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var selSQL = @"SELECT * FROM EMPLOYEE f WHERE f.MAKECALENDARID='" + MID + "' ";
        //DataTable dt = DatabaseHelper.Query_ReturnDatTable(selSQL);
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = selSQL;
        result = DatabaseHelper.RunProcedureForPage(paraPage);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    #endregion


}